<template>
  <div class="cotainer">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索部分 -->
      <el-row class="user-search">
        <!-- 搜索框 -->
        <el-col :span="12">
          <el-input placeholder="请输入查询内容" v-model="users.query" @blur="getUserList()" clearable @clear="getUserList()">
          <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <!-- 新增用户按钮 -->
        <el-col>
          <el-button type="primary" @click="addFormBool = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <template>
        <el-table
          :data="userList"
          stripe
          border
          style="width: 100%">
          <el-table-column
            type="index"
            align="center"
            header-align="center"
            :resizable="false">
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            header-align="center"
            :resizable="false">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            header-align="center"
            :resizable="false">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="电话"
            header-align="center"
            :resizable="false">
          </el-table-column>
          <el-table-column
            prop="role_name"
            label="角色"
            header-align="center"
            :resizable="false">
          </el-table-column>
          <el-table-column
            prop="mg_state"
            label="状态"
            header-align="center"
            width="75px"
            :resizable="false">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="handleState(scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </template>
         </el-table-column>
         <el-table-column
           prop="operation"
           label="操作"
           header-align="center"
           :resizable="false"
           width="178px">
           <template slot-scope="scope">
             <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEditUser(scope.row)"></el-button>
             <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDelUser(scope.row)"></el-button>
             <el-tooltip class="item" effect="dark" content="角色分配" placement="top" :enterable="false">
               <el-button type="warning" size="mini" icon="el-icon-setting" @click="handleDistRoleForm(scope.row)"></el-button>
             </el-tooltip>
           </template>
         </el-table-column>
       </el-table>
      </template>
      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="users.pagenum"
          :page-sizes="[3, 5, 20, 50]"
          :page-size="users.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNum">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加用户弹出框 -->
    <el-dialog title="新增管理员账户" :visible.sync="addFormBool" @close="hanleCloseAdd">
      <el-form status-icon :model="addUserInfo" :rules="addFormRules" ref="addFormRef" label-position="right" label-width="100px">
        <el-form-item
        label="设置账户名"
        prop="username"
        label-width="100px">
          <el-input
          v-model="addUserInfo.username"
          placeholder="请输入新增的管理员账户名称..."></el-input>
        </el-form-item>
        <el-form-item
        label="设置新密码"
        prop="password"
        label-width="100px">
          <el-input
          v-model="addUserInfo.password"
          type="password"
          placeholder="请为新管理员账户设置新的密码..."></el-input>
        </el-form-item>
        <el-form-item
        label="确认新密码"
        prop="repwd"
        label-width="100px">
          <el-input
          v-model="addUserInfo.repwd"
          type="password"
          placeholder="请再次输入新设置的密码..."></el-input>
        </el-form-item>
        <el-form-item
        label="管理员邮箱"
        prop="email"
        label-width="100px">
          <el-input
          v-model="addUserInfo.email"
          placeholder="为便于联络，我们建议您输入管理员邮箱..."></el-input>
        </el-form-item>
        <el-form-item
        label="管理员电话"
        prop="mobile"
        label-width="100px">
          <el-input
          v-model="addUserInfo.mobile"
          placeholder="为便于联络，我们建议您输入管理员手机号码..."></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormBool = false">取 消</el-button>
        <el-button type="primary" @click="handleAddSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑用户弹出框 -->
    <el-dialog :title="`编辑管理员 ${editUserName} 账户信息`" :visible.sync="editFormBool">
      <el-form status-icon :model="editUserInfo" ref="editFormRef" :rules="editFormRules" label-position="right" label-width="100px">
        <el-form-item
        label="管理员账户"
        label-width="100px">
          <el-input
          v-model="editUserInfo.username"
          disabled></el-input>
        </el-form-item>
        <el-form-item
        label="管理员邮箱"
        prop="email"
        label-width="100px">
          <el-input
          v-model="editUserInfo.email"
          placeholder="当前管理员未设置邮箱，我们建议您完善邮箱信息..."></el-input>
        </el-form-item>
        <el-form-item
        label="管理员电话"
        prop="mobile"
        label-width="100px">
          <el-input
          v-model="editUserInfo.mobile"
          placeholder="当前管理员未设置电话，我们建议您完善电话号码..."></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormBool = false">取 消</el-button>
        <el-button type="primary" @click="handleEditSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色分配弹出框 -->
    <el-dialog :title="`为管理员 ${distRoleUser.username} 分配新的权限角色`" :visible.sync="distRoleFormBool" @close="handleDistRoleFormClose">
      <el-form :model="distRoleUser" ref="distRoleFormRef" label-width="100px" label-position="right">
        <!-- 当前用户信息 -->
        <el-form-item label="当前管理员">
          <el-tag
            effect="dark"
            size="medium"
            color="#409EFF">
            {{distRoleUser.username}}
          </el-tag>
        </el-form-item>
          <el-form-item label="当前角色名">
          <el-tag
            effect="dark"
            size="medium"
            color="#F56C6C">
            {{distRoleUser.role_name}}
          </el-tag>
        </el-form-item>
        <!-- 分配校色下拉菜单 -->
        <el-form-item label="选择新角色">
          <el-select v-model="selectRoleId" :placeholder="`请为 ${distRoleUser.username} 设置一个新的管理权限角色...`">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="distRoleFormBool = false">取 消</el-button>
        <el-button type="primary" @click="distRoleFormSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  created () {
    this.getUserList()
  },
  data () {
    // 验证用户名
    var checkUsername = (rule, value, cb) => {
      const regUname = /^[a-zA-Z0-9_-]{4,12}$/
      if (!regUname.test(value)) return cb(new Error('必须由4-12位字母或数字组成[可包含"-", "_"]'))
      cb()
    }
    // 验证密码
    var checkPassword = (rule, value, cb) => {
      const regPassword = /^[0-9]{6}$/
      if (!regPassword.test(value)) return cb(new Error('密码必须由6位数字组成'))
      cb()
    }
    // 验证二次确认密码
    var checkRepwd = (rule, value, cb) => {
      const regPassword = /^[0-9]{6}$/
      if (!regPassword.test(value)) return cb(new Error('密码必须由6位数字组成'))
      if (value !== this.addUserInfo.password) return cb(new Error('两次输入的密码不一致'))
      cb()
    }
    // 验证邮箱
    var checkEmail = (rule, value, cb) => {
      if (this.addUserInfo.email || this.editUserInfo.email) {
        const regEmail = /^\w+@\w+(\.\w+)+$/
        if (!regEmail.test(value)) return cb(new Error('邮箱格式不合法'))
        cb()
      } else {
        cb()
      }
    }
    // 验证手机号
    var checkMobile = (rule, value, cb) => {
      if (this.addUserInfo.mobile || this.editUserInfo.mobile) {
        const regMobile = /^1[34578]\d{9}$/
        if (!regMobile.test(value)) return cb(new Error('手机格式不合法'))
        cb()
      } else {
        cb()
      }
    }
    return {
      users: {
        query: '',
        pagenum: 1,
        pagesize: 3
      },
      // 管理员列表
      userList: [],
      // 用户总数
      totalNum: 0,
      // 添加用户弹出框
      addFormBool: false,
      // 添加用户信息
      addUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: '',
        repwd: ''
      },
      // 编辑用户弹出框
      editFormBool: false,
      // 编辑用户信息
      editUserInfo: {},
      // 新增用户自定义校验规则
      addFormRules: {
        username: [
          { required: true, message: '用户名为必填项', trigger: 'blur' },
          { validator: checkUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码为必填项', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ],
        repwd: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: checkRepwd, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'change' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'change' }
        ]
      },
      // 编辑用户自定义校验规则
      editFormRules: {
        email: [
          { validator: checkEmail, trigger: 'change' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'change' }
        ]
      },
      // 角色分配弹出框
      distRoleFormBool: false,
      // 当前角色信息
      distRoleUser: {
        username: '',
        role_name: '',
        userId: ''
      },
      // 角色列表信息
      rolesList: [],
      // 被选中角色
      selectRoleId: '',
      // 当前编辑管理员
      editUserName: ''
    }
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.users })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.totalNum = res.data.total
    },
    // 改变用户状态
    async handleState (curUser) {
      const { data: res } = await this.$http.put(`users/${curUser.id}/state/${curUser.mg_state}`)
      if (res.meta.status !== 200) {
        curUser.mg_state = !curUser.mg_state
        return this.$message.error(res.meta.msg)
      }
      const flag = curUser.mg_state ? `${curUser.username} 权限已开放！` : `${curUser.username} 权限被禁用！`
      curUser.mg_state ? this.$message.success(flag) : this.$message.warning(flag)
    },
    // 页码范围变化重新获取用户数据
    handleSizeChange (newSize) {
      this.users.pagesize = newSize
      this.getUserList()
    },
    // 当前页码变化获取用户数据
    handleCurrentChange (newPage) {
      this.users.pagenum = newPage
      this.getUserList()
    },
    // 关闭添加用户对话框重置表单
    hanleCloseAdd () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加新用户
    handleAddSubmit () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('用户信息存在不合法信息或不完整')
        const { data: res } = await this.$http.post('users', {
          username: this.addUserInfo.username,
          password: this.addUserInfo.repwd,
          email: this.addUserInfo.email,
          mobile: this.addUserInfo.mobile
        })
        this.addFormBool = false
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 重新获取用户数据
        this.getUserList()
      })
    },
    // 查询编辑用户
    async handleEditUser (curUser) {
      if (!curUser.id) return this.$message.error('用户数据异常，请重试')
      this.editUserName = curUser.username
      const { data: res } = await this.$http.get(`users/${curUser.id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      sessionStorage.setItem('curuser', JSON.stringify(res.data))
      this.editUserInfo = res.data
      this.editFormBool = true
    },
    // 编辑用户提交
    handleEditSubmit () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('存在不合法信息')
        const curuser = JSON.parse(sessionStorage.getItem('curuser'))
        if (this.editUserInfo.email === curuser.email && this.editUserInfo.mobile === curuser.mobile) return this.$message.error('请修改信息后再进行提交')
        if (!this.editUserInfo.id) return this.$message.error('获取用户信息异常，请重试')
        const { data: res } = await this.$http.put(`users/${this.editUserInfo.id}`, {
          email: this.editUserInfo.email,
          mobile: this.editUserInfo.mobile
        })
        this.editFormBool = false
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
    },
    // 删除当前用户
    async handleDelUser (curUser) {
      const confirmRes = await this.$confirm(`确认永久删除管理员 ${curUser.username} 的所有信息?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info(`删除管理员 ${curUser.username} 的操作被终止！`)
      const { data: res } = await this.$http.delete(`users/${curUser.id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(`管理员 ${curUser.userna} 所有信息已被删除！`)
      this.getUserList()
    },
    // 分配角色弹出框
    async handleDistRoleForm (curUser) {
      this.distRoleUser.username = curUser.username
      this.distRoleUser.role_name = curUser.role_name
      this.distRoleUser.userId = curUser.id
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.distRoleFormBool = true
      this.rolesList = res.data
    },
    // 提交角色分配
    async distRoleFormSubmit () {
      if (!this.selectRoleId) return this.$message.warning('未选择新角色,请选择确认后再进行提交!')
      const { data: res } = await this.$http.put(`users/${this.distRoleUser.userId}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.distRoleFormBool = false
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    // 当分配角色对话框关闭清空下拉框选中项
    handleDistRoleFormClose () {
      this.selectRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 12px;
}
.el-card {
  .user-search {
    display: flex;
    margin-bottom: 18px;
    .el-col:first-child {
      margin-right: 16px;
    }
  }
  .el-table {
    margin-bottom: 18px;
  }
}

// 去除tag标签自带边框
.el-tag {
  border: none;
  font-weight: 800;
  font-size: 14px;
}

.el-select {
  width: 100%;
}

</style>
